package com.example.keli;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.example.keli.base.AppConfig;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.utils.SnackbarUtils;
import com.example.keli.base.widget.TabStripView;
import com.example.keli.ui.center.CenterFragment;
import com.example.keli.ui.home.fragment.HomeFragment;
import com.example.keli.ui.list.RankFragment;
import com.example.keli.ui.my.MyFragment;
import com.example.keli.ui.register.LoginAndRegisterActivity;
import com.example.keli.ui.reward.RewardFragment;
import com.example.keli.ui.userinfo.GlobalDialogActivity;
import com.pgyersdk.update.PgyUpdateManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {

    @BindView(R.id.navigateTabBar)
    TabStripView navigateTabBar;
    @BindView(R.id.apply_icon)
    ImageView mApplyIcon;
    private long mkeyTime;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    private String[] tabName = new String[]{"首页", "榜单", "我要报名", "奖励", "我的"};

    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void bindData() {
        initView();
        EventBus.getDefault().register(this);
//        updateVersion();
        postData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateVersion();
    }

    private void updateVersion() {
//        PgyCrashManager.register();
        requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, "需要读写权限",
                new GrantedResult() {
                    @Override
                    public void onResult(boolean granted) {
                        if (granted){
                            new PgyUpdateManager.Builder()
                                    .setForced(true)                //设置是否强制提示更新
                                    // v3.0.4+ 以上同时可以在官网设置强制更新最高低版本；网站设置和代码设置一种情况成立则提示强制更新
                                    .setUserCanRetry(false)         //失败后是否提示重新下载
                                    .setDeleteHistroyApk(true)
                                    .register();
                        }
                    }
                });
    }

    private void initView() {
        //对应xml中的containerId
        navigateTabBar.setFrameLayoutId(R.id.main_container);
        //对应xml中的navigateTabTextColor
        navigateTabBar.setTabTextColor(getResources().getColor(R.color.text_color));
        //对应xml中的navigateTabSelectedTextColor
        navigateTabBar.setSelectedTabTextColor(getResources().getColor(R.color.text_color));

//        //恢复选项状态
//        navigateTabBar.onRestoreInstanceState(savedInstanceState);

        navigateTabBar.addTab(HomeFragment.class, new TabStripView.TabParam(R.drawable.ic_home, R.drawable.ic_home_chosen, R.string.home));
        navigateTabBar.addTab(RankFragment.class, new TabStripView.TabParam(R.drawable.ic_activity, R.drawable.ic_activity_chosen, R.string.rank));
        navigateTabBar.addTab(CenterFragment.class, new TabStripView.TabParam(R.drawable.ic_wall, R.drawable.ic_wall_chosen, R.string.signup));
        navigateTabBar.addTab(RewardFragment.class, new TabStripView.TabParam(R.drawable.ic_chat, R.drawable.ic_chat_chosen, R.string.chat));
        navigateTabBar.addTab(MyFragment.class, new TabStripView.TabParam(R.drawable.ic_me, R.drawable.ic_me_chosen, R.string.my));

        navigateTabBar.setTabSelectListener(new TabStripView.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabStripView.ViewHolder holder) {
                int position = holder.tabIndex;
//                abTitle.setText(tabName[position]);
                if (position == 2) {
                    mApplyIcon.setSelected(true);
                } else {
                    mApplyIcon.setSelected(false);
                }
            }
        });
//        abTitle.setText("首页");
//        getPermissions();
    }

    @OnClick(R.id.apply_icon)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.apply_icon:
                mApplyIcon.setSelected(true);
//                abTitle.setText("我要报名");
                navigateTabBar.setCurrentSelectedTab(2);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String quit_login) {
        if (TextUtils.equals(quit_login, AppConfig.QUIT_LOGIN)) {
            //退出登录通知
            finish();
            Intent intent = new Intent(this, LoginAndRegisterActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
//            toActivity(LoginActivity.class);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void tokenEvent(String token_time_out) {
        if (TextUtils.equals(token_time_out, AppConfig.TOKEN_OUT_TIME)) {
            //token过期通知,弹出全局dialog
            GlobalDialogActivity.start(MainActivity.this);
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void Event(LocationVO locationVO) {
//        //重新定位
//        if(null!=mLocationClient){
//            mLocationClient.startLocation();
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        PgyUpdateManager.unRegister();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (JCVideoPlayer.backPress()) {
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                mkeyTime = System.currentTimeMillis();
                SnackbarUtils.Short(navigateTabBar, "再按一次退出程序").messageColor(Color.WHITE).confirm().gravityFrameLayout(Gravity.BOTTOM).messageCenter().backColor(Color.DKGRAY).show();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    private void postData() {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("appId","1");//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url("https://apecoder.top/getAppSwitch")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    if(TextUtils.equals(dataObject.getString("switchStatus"),"1")){
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
